// FileOpsService：负责文件操作的高层业务逻辑，如还原、对比等
import { getGitHistoryContent, getLocalHistoryContent, localHistoryRestore } from '../tauriApi';
import { invoke } from '@tauri-apps/api/core';

export interface RestoreFileOptions {
  resourceUri: string;
  id: string;
  source: string;
  skipTimelineRefresh?: boolean;
  skipWorkspaceRefresh?: boolean;
}

export interface DiffFileOptions {
  resourceUri: string;
  id: string;
  source: string;
}

/**
 * 文件操作服务层，统一管理文件还原、对比等操作
 * 消除组件层对底层 API 的直接依赖，实现单一责任原则
 */
export class FileOpsService {
  private static instance: FileOpsService;

  static getInstance(): FileOpsService {
    if (!FileOpsService.instance) {
      FileOpsService.instance = new FileOpsService();
    }
    return FileOpsService.instance;
  }

  /**
   * 还原文件到指定历史版本
   * @param options 还原选项
   * @returns Promise<void>
   */
  async restoreFile(options: RestoreFileOptions): Promise<void> {
    const { resourceUri, id, source, skipTimelineRefresh = false, skipWorkspaceRefresh = false } = options;

    try {
      // 1) 读取将要还原的内容（统一大小写：git / Git -> git）
      const normalizedSource = this.normalizeSource(source);
      let content: string;
      
      if (normalizedSource === 'git') {
        content = await getGitHistoryContent(resourceUri, id);
      } else {
        content = await getLocalHistoryContent(resourceUri, id);
      }

      if (content === undefined || content === null) {
        throw new Error(`No content to restore for ${resourceUri} (id: ${id}, source: ${source})`);
      }

      // 2) 写回磁盘
      await localHistoryRestore(resourceUri, content);

      // 3) 发出全局事件，让相关组件自动更新
      this.emitFileRestored({
        resourceUri,
        id,
        source: normalizedSource,
        content,
        skipTimelineRefresh,
        skipWorkspaceRefresh
      });

      console.log(`File restored successfully: ${resourceUri}`);
    } catch (error) {
      console.error('Error in FileOpsService.restoreFile:', error);
      throw error;
    }
  }

  /**
   * 读取文件内容
   * @param filePath 文件路径
   * @returns Promise<string>
   */
  async readFile(filePath: string): Promise<string> {
    try {
      return await invoke<string>('fs_read_text', { path: filePath });
    } catch (error) {
      console.error('Error in FileOpsService.readFile:', error);
      throw error;
    }
  }

  /**
   * 写入文件内容
   * @param filePath 文件路径
   * @param content 文件内容
   * @param createDirs 是否创建目录
   * @returns Promise<void>
   */
  async writeFile(filePath: string, content: string, createDirs: boolean = true): Promise<void> {
    try {
      await invoke('fs_write_text', { path: filePath, content, create_dirs: createDirs });
    } catch (error) {
      console.error('Error in FileOpsService.writeFile:', error);
      throw error;
    }
  }

  /**
   * 获取文件历史内容用于对比
   * @param options 对比选项
   * @returns Promise<string>
   */
  async getHistoryContent(options: DiffFileOptions): Promise<string> {
    const { resourceUri, id, source } = options;
    const normalizedSource = this.normalizeSource(source);

    try {
      if (normalizedSource === 'git') {
        return await getGitHistoryContent(resourceUri, id);
      } else {
        return await getLocalHistoryContent(resourceUri, id);
      }
    } catch (error) {
      console.error('Error in FileOpsService.getHistoryContent:', error);
      throw error;
    }
  }

  /**
   * 统一 source 字段的大小写规范（git/Git -> git, local-history/Local-History -> local-history）
   */
  private normalizeSource(source: string): string {
    const src = String(source || '').toLowerCase().trim();
    if (src === 'git') return 'git';
    if (src.includes('local') || src.includes('history')) return 'local-history';
    return src;
  }

  /**
   * 发出文件还原事件，供其他组件监听和自动更新
   */
  private emitFileRestored(params: {
    resourceUri: string;
    id: string;
    source: string;
    content: string;
    skipTimelineRefresh?: boolean;
    skipWorkspaceRefresh?: boolean;
  }) {
    // 使用简单的自定义事件机制，避免引入重型事件库
    const event = new CustomEvent('file-ops:restored', {
      detail: params
    });
    
    // 在全局 window 对象上触发事件
    if (typeof window !== 'undefined') {
      window.dispatchEvent(event);
    }

    // 也可以直接调用必要的刷新逻辑
    this.handleFileRestored(params);
  }

  /**
   * 处理文件还原后的自动刷新逻辑
   */
  private async handleFileRestored(params: {
    resourceUri: string;
    skipTimelineRefresh?: boolean;
    skipWorkspaceRefresh?: boolean;
  }) {
    const { resourceUri, skipTimelineRefresh, skipWorkspaceRefresh } = params;

    // 4) 刷新时间线（如果当前时间线正聚焦于该 URI）
    if (!skipTimelineRefresh) {
      try {
        const { useTimelineStore } = await import('../stores/timeline');
        const timelineStore = useTimelineStore();
        if (timelineStore.currentUri === resourceUri) {
          await timelineStore.refreshTimeline();
        }
      } catch (e) {
        console.warn('Failed to refresh timeline after restore:', e);
      }
    }

    // 5) 刷新工作区（触发文件树/监听同步）
    if (!skipWorkspaceRefresh) {
      try {
        const { useWorkspaceStore } = await import('../stores/workspace');
        const store = useWorkspaceStore();
        store.refreshWorkspace();
      } catch (e) {
        console.warn('Failed to refresh workspace after restore:', e);
      }
    }
  }
}

// 导出单例实例
export const fileOpsService = FileOpsService.getInstance();